<template>
    <div>
        <!-- 使用 Element Plus 的标签页组件，用于切换不同的登录方式 -->
        <el-tabs v-model="activeTab">
            <!-- 登录标签页内容 -->
            <el-tab-pane label="登录" name="login">
                <!-- 登录标题 -->
                <h2 class="login-title">平台管理登录</h2>
                <!-- 登录表单 -->
                <el-form 
                    :model="loginForm" 
                    label-width="100px"
                    :rules="loginRules"
                    ref="loginFormRef"
                >
                    <!-- 账号输入项 -->
                    <el-form-item label="账号" prop="number">
                        <el-input 
                            v-model="loginForm.number" 
                            placeholder="请输入平台管理员账号"
                            clearable
                        />
                    </el-form-item>
                    <!-- 密码输入项 -->
                    <el-form-item label="密码" prop="password">
                        <el-input 
                            v-model="loginForm.password" 
                            type="password"
                            placeholder="请输入密码"
                            show-password
                        />
                    </el-form-item>
                    <!-- 验证码输入项 -->
                    <el-form-item label="验证码" prop="captcha">
                        <el-row :gutter="10">
                            <el-col :span="14">
                                <el-input 
                                    v-model="loginForm.captcha" 
                                    placeholder="请输入验证码"
                                    clearable
                                />
                            </el-col>
                            <el-col :span="10">
                                <div class="captcha-container">
                                    <img :src="captchaImage" class="captcha-image" @click="refreshCaptcha" alt="验证码">
                                    <el-button 
                                        type="text" 
                                        class="refresh-btn"
                                        @click="refreshCaptcha"
                                    >
                                        刷新
                                    </el-button>
                                </div>
                            </el-col>
                        </el-row>
                    </el-form-item>
                    <!-- 登录按钮 -->
                    <el-form-item>
                        <el-button 
                            type="primary" 
                            @click="handleLogin"
                            :loading="loginStore.loginLoading"
                        >
                            登录
                        </el-button>
                    </el-form-item>
                    
                    <!-- 第三方登录选项 -->
                    <div class="third-party-login">
                        <span class="separator">其他登录方式</span>
                        <div class="login-icons">
                            <el-icon class="login-icon" @click="handleThirdPartyLogin('wechat')">
                                <Wechat />
                            </el-icon>
                            <el-icon class="login-icon" @click="handleThirdPartyLogin('qq')">
                                <Qq />
                            </el-icon>
                            <el-icon class="login-icon" @click="handleThirdPartyLogin('alipay')">
                                <Alipay />
                            </el-icon>
                        </div>
                    </div>
                </el-form>
            </el-tab-pane>
        </el-tabs>
    </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { ElMessage, ElIcon } from 'element-plus';
import { useRouter } from 'vue-router';
import { useLoginStore } from '../../stores/index.js';
// 引入第三方图标
// import { Wechat, Qq, Alipay } from '@element-plus/icons-vue';

// 获取路由实例，用于页面跳转
const router = useRouter();

// 当前激活的标签页名称，默认为 'login'
const activeTab = ref('login');

// 表单引用，用于调用表单验证方法
const loginFormRef = ref();

// 获取登录状态管理实例
const loginStore = useLoginStore();

// 验证码图片地址
const captchaImage = ref('');
// 生成的验证码文本（用于验证）
const generatedCaptcha = ref('');

/**
 * 登录表单数据对象
 * 包含用户名、密码、验证码和登录类型
 */
const loginForm = reactive({
    number: '',
    password: '',
    captcha: '', // 验证码输入
    loginType: 'platform'  // 指定登录类型
});


/**
 * 表单验证规则配置
 * 定义了账号、密码和验证码的验证要求
 */
const loginRules = {
    number: [
        { required: true, message: '请输入账号', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' }
    ],
    captcha: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { 
            validator: (rule, value, callback) => {
                if (value.toLowerCase() !== generatedCaptcha.value.toLowerCase()) {
                    callback(new Error('验证码不正确'));
                } else {
                    callback();
                }
            },
            trigger: 'blur'
        }
    ]
};

/**
 * 生成随机验证码
 * @returns {string} 随机生成的4位字母数字组合
 */
const generateRandomCaptcha = () => {
    const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    let result = '';
    for (let i = 0; i < 4; i++) {
        result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return result;
};

/**
 * 生成验证码图片（静态模拟）
 */
const generateCaptchaImage = () => {
    const captcha = generateRandomCaptcha();
    generatedCaptcha.value = captcha;
    
    // 生成一个简单的验证码图片数据URL（静态模拟）
    const canvas = document.createElement('canvas');
    canvas.width = 120;
    canvas.height = 40;
    const ctx = canvas.getContext('2d');
    
    // 背景色
    ctx.fillStyle = '#f3f3f3';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // 干扰线
    for (let i = 0; i < 5; i++) {
        ctx.strokeStyle = `rgb(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255})`;
        ctx.beginPath();
        ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
        ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
        ctx.stroke();
    }
    
    // 绘制验证码
    ctx.font = 'bold 24px Arial';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillStyle = '#333';
    
    // 每个字符随机位置和旋转
    for (let i = 0; i < captcha.length; i++) {
        const char = captcha[i];
        const x = 20 + i * 25;
        const y = canvas.height / 2;
        const rotate = (Math.random() - 0.5) * 0.5;
        
        ctx.save();
        ctx.translate(x, y);
        ctx.rotate(rotate);
        ctx.fillText(char, 0, 0);
        ctx.restore();
    }
    
    captchaImage.value = canvas.toDataURL('image/png');
};

/**
 * 刷新验证码
 */
const refreshCaptcha = () => {
    generateCaptchaImage();
    loginForm.captcha = ''; // 清空输入
};

/**
 * 处理第三方登录
 * @param {string} type 第三方登录类型：wechat, qq, alipay
 */
const handleThirdPartyLogin = async (type) => {
    // 显示加载状态
    loginStore.loginLoading = true;
    
    try {
        // 模拟第三方登录API请求（静态数据）
        await new Promise(resolve => setTimeout(resolve, 1000));
        
        // 静态模拟登录结果
        const mockResults = {
            wechat: { code: 200, message: '微信登录成功' },
            qq: { code: 200, message: 'QQ登录成功' },
            alipay: { code: 200, message: '支付宝登录成功' }
        };
        
        const res = mockResults[type];
        
        if (res.code === 200) {
            ElMessage.success(res.message);
            router.push('/platform/home');
        } else {
            ElMessage.error(res.message || '第三方登录失败');
        }
    } catch (error) {
        console.log('第三方登录失败:', error);
        ElMessage.error('登录过程出错，请重试');
    } finally {
        // 关闭加载状态
        loginStore.loginLoading = false;
    }
};

/**
 * 处理用户登录逻辑
 * 执行表单验证并提交登录请求，根据角色跳转到对应页面
 * @returns {Promise<void>}
 */
const handleLogin = async () => {
    try {
        // 触发表单rules验证
        await loginFormRef.value.validate();
        
        // 提交登录请求
        const res = await loginStore.postLogin(loginForm);
        
        // 根据用户角色进行页面跳转
        if (res.code === 200) {
            router.push('/platform/home');
        }
    } catch (error) {
        console.log('登录失败:', error);
        // 验证失败时刷新验证码
        if (error.name === 'ValidationError') {
            refreshCaptcha();
        }
    }
};

// 初始化生成验证码
generateCaptchaImage();
</script>

<style scoped>
@import '../../styles/login_styles.css';

/* 验证码样式 */
.captcha-container {
    display: flex;
    align-items: center;
    gap: 10px;
}

.captcha-image {
    width: 80px;
    height: 40px;
    cursor: pointer;
    border-radius: 4px;
}

.refresh-btn {
    padding: 0;
    color: #409eff;
}

/* 第三方登录样式 */
.third-party-login {
    margin-top: 20px;
    text-align: center;
}

.separator {
    display: inline-block;
    margin-bottom: 15px;
    color: #999;
    font-size: 14px;
    position: relative;
}

.separator::before,
.separator::after {
    content: '';
    position: absolute;
    top: 50%;
    width: 60px;
    height: 1px;
    background-color: #e5e7eb;
}

.separator::before {
    left: -70px;
}

.separator::after {
    right: -70px;
}

.login-icons {
    display: flex;
    justify-content: center;
    gap: 30px;
}

.login-icon {
    font-size: 28px;
    cursor: pointer;
    transition: all 0.3s ease;
}

.login-icon:hover {
    transform: scale(1.2);
}

/* 图标颜色 */
:deep(.el-icon-wechat) {
    color: #07C160;
}

:deep(.el-icon-qq) {
    color: #12B7F5;
}

:deep(.el-icon-alipay) {
    color: #1677FF;
}
</style>